from flask import render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user
from routes import learning_bp
from extensions import db
from models import Course
from forms.learning import CourseForm

@learning_bp.route('/')
def index():
    page = request.args.get('page', 1, type=int)
    courses = Course.query.order_by(Course.created_at.desc()).paginate(
        page=page, per_page=10, error_out=False
    )
    return render_template('learning/index.html', courses=courses)

@learning_bp.route('/<int:id>')
def detail(id):
    course = Course.query.get_or_404(id)
    course.views += 1
    db.session.commit()
    return render_template('learning/detail.html', course=course)

@learning_bp.route('/create', methods=['GET', 'POST'])
@login_required
def create():
    if current_user.role != 'admin':
        flash('只有管理员可以创建课程！', 'danger')
        return redirect(url_for('learning.index'))
        
    form = CourseForm()
    if form.validate_on_submit():
        course = Course(
            title=form.title.data,
            description=form.description.data,
            content=form.content.data,
            user_id=current_user.id
        )
        db.session.add(course)
        db.session.commit()
        flash('课程创建成功！', 'success')
        return redirect(url_for('learning.detail', id=course.id))
    return render_template('learning/create.html', form=form)

@learning_bp.route('/<int:id>/edit', methods=['GET', 'POST'])
@login_required
def edit(id):
    course = Course.query.get_or_404(id)
    if current_user.role != 'admin':
        flash('只有管理员可以编辑课程！', 'danger')
        return redirect(url_for('learning.detail', id=id))
        
    form = CourseForm(obj=course)
    if form.validate_on_submit():
        course.title = form.title.data
        course.description = form.description.data
        course.content = form.content.data
        db.session.commit()
        flash('课程更新成功！', 'success')
        return redirect(url_for('learning.detail', id=id))
    return render_template('learning/create.html', form=form, course=course)

@learning_bp.route('/<int:id>/delete', methods=['POST'])
@login_required
def delete(id):
    course = Course.query.get_or_404(id)
    if current_user.role != 'admin':
        flash('只有管理员可以删除课程！', 'danger')
        return redirect(url_for('learning.detail', id=id))
        
    db.session.delete(course)
    db.session.commit()
    flash('课程已删除！', 'success')
    return redirect(url_for('learning.index')) 